package com.yangsir.mysite.filter;

import com.yangsir.mysite.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * java 8
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginFilterCheck implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");//不可以传*
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        response.setHeader("Access-Control-Allow-Credentials", "true");//这行是关键
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);//解决预处理
        }
        // 1、获取本次请求的url
        String requestUrl = request.getRequestURI();
        String[] split = requestUrl.split("/");
        if (split[1].equals("user")&&(split[2].equals("getAllUser") || // 获取所有用户信息 (管理员)
                split[2].equals("createUser") || // 创建用户 (管理员)
                split[2].equals("getUserByStr") || // 搜索用户信息 (管理员)
                split[2].equals("getUserByRole") || // 根据角色查询用户信息 (管理员)
                split[2].equals("deleteUser") || // 删除用户 (管理员)
                split[2].equals("deactivateUser"))){ // 禁用或启动用户 (管理员)
            User user = (User) request.getSession().getAttribute("user");
            if (user == null || user.getUserRole() != 2) return;
            filterChain.doFilter(request,response);
            return;
        }
        if (split[1].equals("article")&&( split[2].equals("save") ||
                split[2].equals("myArticles") ||
                split[2].equals("getArticlesByStr") ||
                split[2].equals("deleteArticle"))) {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null || user.getUserRole() == 0) return;
            filterChain.doFilter(request,response);
            return;
        }
        filterChain.doFilter(request,response);
    }
    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}
